//
//  BaseService.m
//  LotteryClient
//
//  Created by SunYu on 14-2-6.
//  Copyright (c) 2014年 SunYu. All rights reserved.
//


#import "BaseService.h"
#import "BaseCacheManager+NSCoding.h"


@implementation BaseService

DEF_STATIC_PROPERTY_INT(baseType, BaseTypeService)

- (void)dealloc
{
	if (_requsetDictionary)
	{
		for (NSString *key in [_requsetDictionary allKeys])
		{
			AFHTTPRequestOperation *request = [_requsetDictionary objectForKey:key];
			[request cancel];
		}
		
		[_requsetDictionary removeAllObjects];
	}

}

- (void)setWrapper:(AFHTTPRequestOperation *)wrapper ForKey:(NSString *)key
{
	if ([self.requsetDictionary objectForKey:key])
	{
		[[self.requsetDictionary objectForKey:key] cancel];
		[self.requsetDictionary removeObjectForKey:key];

	}
	
	[self.requsetDictionary setValue:wrapper forKey:key];
}

- (void)removeWrapperForKey:(NSString *)key
{
	if ([self.requsetDictionary objectForKey:key])
	{
		[[self.requsetDictionary objectForKey:key] cancel];
		[self.requsetDictionary removeObjectForKey:key];
		
	}
}

#pragma --
#pragma --mark init
- (instancetype)initDefaultBaseUrlString
{
    self = [self initWithBaseUrlString:kBaseWebServiceUrl];
    return self;
}

+ (instancetype)serviceWithDefaultBaseUrlString
{
    return  [self serviceWithBaseUrlString:kBaseWebServiceUrl];
}

- (instancetype)initWithBaseUrlString:(NSString *)baseUrlString
{
    self = [super init];
    if (self)
    {
        self.baseUrlString = baseUrlString;
    }

    return self;
}

+ (instancetype)serviceWithBaseUrlString:(NSString *)baseUrlString
{
    return [[self alloc] initWithBaseUrlString:baseUrlString];
}

- (NSMutableDictionary *)requsetDictionary
{
	if (!_requsetDictionary)
	{
		_requsetDictionary = [[NSMutableDictionary alloc] init];
	}
	
	return _requsetDictionary;
}


#pragma --
#pragma --mark customer
- (NSMutableDictionary *)defaultRequestParameterDictionary
{
    return nil;
}






- (AFHTTPRequestOperation *)beginRequestWithRelativePath:(NSString *)relativePath
										 parameterObject:(id)object
										   responseClass:(NSString *)className
											 finishBlock:(RequestFinishBlock)finishBlock
{
	return [self beginRequestWithRelativePath:relativePath
								   postAction:YES
							  parameterObject:object
								responseClass:className
								  finishBlock:finishBlock];
}


- (AFHTTPRequestOperation *)beginGetRequestWithRelativePath:(NSString *)relativePath
											parameterObject:(id)object
											  responseClass:(NSString *)className
												finishBlock:(RequestFinishBlock)finishBlock
{
	return [self beginRequestWithRelativePath:relativePath
								   postAction:NO
							  parameterObject:object
								responseClass:className
								  finishBlock:finishBlock];
}


- (AFHTTPRequestOperation *)beginRequestWithRelativePath:(NSString *)relativePath
											  postAction:(BOOL)post
										 parameterObject:(id)object
										   responseClass:(NSString *)className
											 finishBlock:(RequestFinishBlock)finishBlock
{
	//发送数据字典
	NSMutableDictionary *temPostDictionary = [NSMutableDictionary dictionary];
	
	if ([object isKindOfClass:[NSDictionary class]])
	{
		[temPostDictionary setDictionary:object];
	}
	else
	{
		if ([object isKindOfClass:[BaseEntity class]])
		{
			NSDictionary *temDic = [object dictionaryForJson];
			if (!temDic)
			{
				temDic = [object getPropertyNameAndValue];
			}
			[temPostDictionary setDictionary:temDic];
		}
	}
	
	
	NSString *urlString = [NSString stringWithFormat:@"%@%@",
						   self.baseUrlString,
						   relativePath];
	NSString *temString = [self.defaultRequestParameterDictionary createStringUrlParameter];

	NSMutableURLRequest *request = nil;

	if (!post)
	{
		[temPostDictionary addEntriesFromDictionary:[self defaultRequestParameterDictionary]];
		if (CHECK_VALID_STRING(temString))
		{
			urlString = [urlString stringByAppendingFormat:@"?%@",temString];
			
		}
		
//		request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

        AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];

        request = [requestSerializer requestWithMethod:@"GET"
                                             URLString:urlString
                                            parameters:temPostDictionary
                                                 error:nil];

	}
	
	else
	{
		
	NSMutableDictionary *fileDictionary = [NSMutableDictionary dictionary];

		
	 [temPostDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
		 if ([obj isKindOfClass:[NSData class]])
		 {
			 [fileDictionary setObject:obj forKey:key];
		 }
		 else if ([obj isKindOfClass:[UIImage class]])
		 {
			 NSData *data =  UIImageJPEGRepresentation((UIImage *)obj, 1);
			 [fileDictionary setObject:data forKey:key];
			 
		 }
	 }];
		
		
		
		{
			[temPostDictionary removeObjectsForKeys:[fileDictionary allKeys]];
			
			AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
			
			request = [requestSerializer multipartFormRequestWithMethod:@"POST"
															  URLString:urlString
															 parameters:temPostDictionary
											  constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
												  NSArray *array = [fileDictionary allKeys];
												  for (NSString *key in array)
												  {
													  NSData *fileData = [fileDictionary objectForKey:key];
													  [formData appendPartWithFileData:fileData
																				  name:key 
																			  fileName:[NSString stringWithFormat:@"%@.jpg",key]
																			  mimeType:@"image/jpeg"];
												  }
												  
											  }
																  error:nil];
			
		}

		
	}
		
	AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
	
	[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
	 {
		 BaseResponse *response = nil;
		 response = [(BaseResponse *) [NSClassFromString(className) alloc] initWithResultData:responseObject];
		 if (!response)
		 {
			 response = [[BaseResponse alloc] initWithResultData:responseObject];
		 }

		 response.httpResponseCode = operation.response.statusCode;
		 response.requestUrlString = urlString;
		 response.requestParamter  = object;
		 
		 
		 [response  saveToFileWithFileName:[[operation.request.URL absoluteString] md5String] withPath:[BaseCacheManager  cachePath]];
		 
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }
	 }
											failure:^(AFHTTPRequestOperation *operation, NSError *error)
	 {
		 BaseResponse *response = [BaseCacheManager loadObjectFromFile:[[operation.request.URL absoluteString] md5String]
															 storePath:[BaseCacheManager cachePath]];
		 
		 response = [[BaseResponse alloc] init];
		 response.success = NO;
		 response.httpResponseCode = [error code];
#ifdef TESTVERSION
		 response.status = [NSString stringWithFormat:@"%ld",(long)[error code]];
		 
		 response.desc = [error description];
#else
		 response.err_msg = kInternetConnectionError;
#endif
		 
		 //		 DLog(@"%@", error);
		 response.requestUrlString = urlString;
		 response.requestParamter  = temPostDictionary;
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }

		 
		 response.httpResponseCode = operation.response.statusCode;
		 response.requestUrlString = urlString;
		 response.requestParamter  = object;
		 
	 }];

	[requestOperation start];
	
	return  requestOperation;
	
}

- (AFHTTPRequestOperation *)beginUploadWithRelativePath:(NSString *)relativePath
											 imageArray:(NSArray *)imageArray
										  responseClass:(NSString *)className
											finishBlock:(RequestFinishBlock)finishBlock
{
	
	NSString                *url               = [NSString stringWithFormat:@"%@%@",
												  self.baseUrlString,
												  relativePath];
	
	AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
	
	NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:@"POST"
																		   URLString:url
																		  parameters:nil
														   constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
															   
															   int          i = 0;
															   for (UIImage *eachImage in imageArray)
															   {
																   NSData *imageData = UIImageJPEGRepresentation(eachImage, 0.5);
																   [formData appendPartWithFileData:imageData
																							   name:[NSString stringWithFormat:@"file%d",
																									 i]
																						   fileName:[NSString stringWithFormat:@"ooo%d.jpg",
																									 i]
																						   mimeType:@"image/jpeg"];
																   i++;
															   }
														   }
																			   error:nil];
	
	AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
	[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
	 {
		 BaseResponse *response = nil;
		 response = [(BaseResponse *) [NSClassFromString(className) alloc] initWithResultData:responseObject];
		 if (!response)
		 {
			 response = [[BaseResponse alloc] initWithResultData:responseObject];
		 }
		 response.requestUrlString = url;
		 response.requestParamter  = nil;
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }

		 
	 }
											failure:^(AFHTTPRequestOperation *operation, NSError *error)
	 {
		 BaseResponse *response = nil;
		 
		 response = [[BaseResponse alloc] init];
		 response.success = NO;
#ifdef TESTVERSION
		 response.status = [NSString stringWithFormat:@"%ld",(long)[error code]];
		 
		 response.desc = [error description];
#else
		 response.desc = kInternetConnectionError;
#endif
		 
		 DLog(@"%@", error);
		 response.requestUrlString = url;
		 response.requestParamter  = nil;
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }

	 }];
	
	[requestOperation start];
	
	return requestOperation;
}


- (AFHTTPRequestOperation *)beginUploadWithRelativePath:(NSString *)relativePath
											 imageArray:(NSArray *)imageArray
											  otherPara:(NSDictionary *)dictionary
										  responseClass:(NSString *)className
											finishBlock:(RequestFinishBlock)finishBlock
{
	
	NSString                *url               = [NSString stringWithFormat:@"%@%@",
												  self.baseUrlString,
												  relativePath];
	
	AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
	
	NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:@"POST"
																		   URLString:url
																		  parameters:dictionary
														   constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
															   
															   int          i = 0;
															   for (UIImage *eachImage in imageArray)
															   {
																   NSData *imageData = UIImageJPEGRepresentation(eachImage, 0.5);
																   [formData appendPartWithFileData:imageData
																							   name:[NSString stringWithFormat:@"file%d",
																									 i]
																						   fileName:[NSString stringWithFormat:@"ooo%d.jpg",
																									 i]
																						   mimeType:@"image/jpeg"];
																   i++;
															   }
														   }
																			   error:nil];
	
	AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
	[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
	 {
		 BaseResponse *response = nil;
		 response = [(BaseResponse *) [NSClassFromString(className) alloc] initWithResultData:responseObject];
		 if (!response)
		 {
			 response = [[BaseResponse alloc] initWithResultData:responseObject];
		 }
		 response.requestUrlString = url;
		 response.requestParamter  = nil;
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }

		 
	 }
											failure:^(AFHTTPRequestOperation *operation, NSError *error)
	 {
		 BaseResponse *response = nil;
		 
		 response = [[BaseResponse alloc] init];
		 response.success = NO;
#ifdef TESTVERSION
		 response.status = [NSString stringWithFormat:@"%ld",(long)[error code]];
		 
		 response.desc = [error description];
#else
		 response.desc = kInternetConnectionError;
#endif
		 
		 DLog(@"%@", error);
		 response.requestUrlString = url;
		 response.requestParamter  = nil;
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }

	 }];
	
	[requestOperation start];
	return requestOperation;
	
}



@end
